package com.tongji;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class BroadcastThread extends Thread {
	private Handler mHandler;
	public BroadcastThread(Handler handler) {
		mHandler = handler;
	}
	
	private void sendNotFoundMessage() {
		Message msg = mHandler.obtainMessage();
		Bundle data = new Bundle();
		data.putString("Commond", "notfound");
		msg.setData(data);
		mHandler.sendMessage(msg);
	}
	
	private void sendFoundMessage(int addr, int port) {
		Message msg = mHandler.obtainMessage();
		Bundle data = new Bundle();
		data.putString("Commond", "found");
		data.putInt("FindingAddr", addr);
		data.putInt("FindingPort", port);
		msg.setData(data);
		mHandler.sendMessage(msg);
	}
	
	public void run() {
		DatagramSocket socketSearch = null;
		try {
			byte [] searchBuffer = new byte[512];
			socketSearch = new DatagramSocket(56789);
			DatagramPacket packetSearch = new DatagramPacket(searchBuffer, searchBuffer.length);
			socketSearch.setSoTimeout(5000);
			socketSearch.receive(packetSearch);
			int receivedLen = packetSearch.getLength();
			if (receivedLen >= 8) {
				int addr = ByteTools.byte2Int(searchBuffer);
				int port = ByteTools.byte2Int(searchBuffer, 4);
				sendFoundMessage(addr, port);
			}
			else  {
				sendNotFoundMessage();
			}
			socketSearch.close();
		} catch (SocketException e1) {
			sendNotFoundMessage();
			e1.printStackTrace();
		} catch (SocketTimeoutException e) {
			sendNotFoundMessage();
			if (socketSearch != null)
				socketSearch.close();
		} catch (IOException e) {
			sendNotFoundMessage();
			e.printStackTrace();
		}
	}
}
